package com.yoke.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by jiangzeyin on 2017/7/4.
 */
public class Md5Util {

    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于获取一个String的md5值
     *
     * @param str
     * @return
     */
    public static String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString().toUpperCase();
    }

    /**
     * @param file
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static String getFileMD5(File file) throws IOException, NoSuchAlgorithmException {
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        byte buffer[] = new byte[1024];
        int len;
        MessageDigest digest = MessageDigest.getInstance("MD5");
        FileInputStream in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
        in.close();
        StringBuilder sb = new StringBuilder();
        for (byte t : digest.digest()) {
            String s = Integer.toHexString(t & 0xFF);
            if (s.length() == 1)
                s = "0" + s;
            sb.append(s);
        }
        // BigInteger bigInt = new BigInteger(1, );
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println(getMd5("hello world"));
    }
}
